'''
获取海洋格网
'''

import os
import time
import sys

root_path = r"__file__"                                                                     # 添加PyDGGS路径
if root_path not in sys.path:
    sys.path.insert(0, root_path)

from PyDGGS.PyDGGS import *
from common import level, element_type                                                      # 导入层级和要素类型

input_dir = os.path.join(os.path.dirname(r'__file__'))                                      # 数据位置
tiff_file = os.path.join(input_dir, "input", "ETOPO1GridTIFF","ETOPO1GridTIFF.json")        # 输入GridTIFF
ocean_grid_gridtiff  = os.path.join(input_dir, "output", "Ocean_Grid")                      # 输出目录

def extractOceanGridFromElevation(level, element_type, input_dir, output_dir):
    """
    从GridTIFF中提取海洋格网并进行二值化处理
    
    param level:            格网层级
    param grid_type:        格网类型
    param element_type:     要素类型
    param output_dir:       输出目录
    """
    
    # 读取10个基础菱形
    layer = DGGSFieldLayerInt()
    layer.loadFromFile(input_dir)

    # 读取波段
    bandId = 0 
    band =layer.getBand(bandId)

    for base_partition in range(1,11):

        print(f"开始处理基础菱形: {base_partition}")

        # 计算格元
        for row in range(0, rowMaxSize(level)):
            for col in range(0, rowMaxSize(level)):
                code = DGGSElementCode()
                code.elementType = element_type
                code.level = level
                code.basePartition = base_partition
                code.row = row
                code.col = col
                value =band.getData(code)

                if value > 0:   # 海拔大于0的陆地设为0
                    band.setData(code, noData )
                else:    
                    band.setData(code, 1 )

    layer.saveToFile(output_dir)
        
 
def main():
    # 调用函数从GridTIFF提取海洋格网，保存为gridtiff
    extractOceanGridFromElevation(level, element_type, tiff_file, ocean_grid_gridtiff)

if __name__ == "__main__":
    start_time = time.time()
    main()
    end_time = time.time()
    execution_time = end_time - start_time
    print(f"程序执行时间: {execution_time} 秒")